package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebFilter("/login")
//登录时进行校验
public class LoginFilter implements Filter {
    private Object JwtsUtils;

    //Filter的执行流程；

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求url--但是现在上面的几个参数无法使用，就需要找到子类方法
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String uri = httpServletRequest.getRequestURI();

        //因为第一次登录时没有令牌的，所以第一次直接通过
        if("/login".equals(uri)){
            //如果是登录直接放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;//注意一旦是登陆就立刻结束
        }
       //前端通过请求头，传递Token
        //如果不是登录，获取Token---现在就是获取请求头
       String token =  httpServletRequest.getHeader("Tokrn");
        //现在就是校验是否有Token(或则是说为不为空)
        if(token!=null&&token!=""){
            try {
                //校验成功，直接放行parseJWT
            // Claims claims =  JwtsUtils.parseJWT(token);
               Claims claims = JwtUtils.parseJWT(token);
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;

            }catch ( Exception e){
                e.printStackTrace();

            }

        }
        //响应错误信息
        Result error =   Result.error("not_login");
        //下载将一json的格式转换给前端
        String jsonobject =  JSONObject.toJSONString(error);
        httpServletResponse.getWriter().write(jsonobject);

    }
    //请求---->放行前逻辑---->放行---->资源---->放行后逻辑
}
